package com.ruoyi.planthopper.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.planthopper.domain.InvesInfo;
import com.ruoyi.planthopper.domain.QueryCondition;
import com.ruoyi.planthopper.domain.RetForExcelSheet2;
import com.ruoyi.planthopper.mapper.InvesMapper;
import com.ruoyi.planthopper.mapper.PlantExportMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: class by cxf
 * @author: AbrahamBill
 * @date: 2022/7/25
 **/
@Slf4j
@RestController
public class PlantExportController extends BaseController {

    @Autowired
    PlantExportMapper plantExportMapper;

    @Autowired
    InvesMapper invesMapper;

    @GetMapping("/getplottest")
    public AjaxResult getplotTest(QueryCondition queryCondition){
        List<InvesInfo> query_lst = plantExportMapper.selectInvesAllListByCondition(queryCondition);
        return AjaxResult.success(query_lst);
    }
    @GetMapping("/getInvesInfoByDayAndPlot")
    public AjaxResult getInvesInfoByDayAndPlot(QueryCondition queryCondition){
        //返回符合查询条件的所有调查信息
        List<InvesInfo> query_lst = plantExportMapper.selectInvesAllListByCondition(queryCondition);
        //返回前端所展示的调查数据统计信息
        List<RetForExcelSheet2> ret_for_cal = new ArrayList<>();
        //遍历所有的调查信息，进行按照日期、地块的统计
        String day = "";
        String plot = "";
        int count = 0;
        RetForExcelSheet2 current_ret = null;
        for(InvesInfo info:query_lst){
            //判断是不是到下一个日期的边界
            if((!info.getInsertDate().equals(day))||(!info.getPlotName().equals(plot))){
                if(current_ret!=null){
                    current_ret.setImgCount(count+1);
                    count = 0;
                    ret_for_cal.add(current_ret);
                }
                current_ret = new RetForExcelSheet2(info);
                day = info.getInsertDate();
                plot = info.getPlotName();
            }//不是边界，则做数据加和
            else{
                current_ret.SameDayAdd(info);
                count += 1;
            }
        }
        if(current_ret!=null){
            current_ret.setImgCount(count+1);
            ret_for_cal.add(current_ret);
        }
        return AjaxResult.success(ret_for_cal);
    }

    @GetMapping("/getExportResultTest")
    public AjaxResult test(QueryCondition queryCondition, HttpServletResponse response) throws IOException {
        //以下为生成表1所需要的list
        List<InvesInfo> lst = plantExportMapper.selectInvesAllListByCondition(queryCondition);
//        lst.sort((el1,el2)->el1.getInsertDate().compareTo(el2.getInsertDate()));//已解决该问题，只要数据库中对两个字段先后排序即可
        //以下为生成表2所需要的list
        List<RetForExcelSheet2> ret_sheet2 = new ArrayList<>();
        String day = "";
        String plot = "";
        int count = 0;
        RetForExcelSheet2 current_ret = null;
        //注意：以下操作需要有序，且第一顺序为time、第二顺序为地块名称
        for(InvesInfo info:lst){
            try{
                info.getPlotName().equals(plot);
            }catch (Exception e){
                info.setPlotName("地块名称为空！");
            }
            //判断是不是到下一个日期的边界
            if ((!info.getInsertDate().equals(day)) || (!info.getPlotName().equals(plot))) {
                if (current_ret != null) {
                    current_ret.setImgCount(count + 1);
                    count = 0;
                    ret_sheet2.add(current_ret);
                }
                current_ret = new RetForExcelSheet2(info);
                day = info.getInsertDate();
                plot = info.getPlotName();
//                   System.out.println("new...........................");
            }//不是边界，则做数据加和
            else {
                count += 1;
                current_ret.SameDayAdd(info);
//                   System.out.println("add...........................");
            }
        }
        //最后一个 RetForExcelSheet2实例不为空则添加
        if(current_ret!=null){
            current_ret.setImgCount(count+1);
            ret_sheet2.add(current_ret);
        }
        //excel导出
//        response.setContentType("application/vnd.ms-excel");
//        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
//        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码
        try {
            String fileName = URLEncoder.encode("searchTable.xls", "UTF-8");
            response.setContentType("application/msexcel;charset=UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");
            //新建ExcelWriter
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
            //获取sheet0对象
            WriteSheet mainSheet = EasyExcel.writerSheet(0, "统计信息").head(RetForExcelSheet2.class).build();
            //向sheet0写入数据 传入空list这样只导出表头
            excelWriter.write(ret_sheet2, mainSheet);
            //获取sheet1对象
            WriteSheet detailSheet = EasyExcel.writerSheet(1, "详细信息").head(InvesInfo.class).build();
            //向sheet1写入数据 传入空list这样只导出表头
            excelWriter.write(lst, detailSheet);
            //关闭流
            excelWriter.finish();
        }catch (Exception e){
            return AjaxResult.error("导出失败",e);
        }
        return AjaxResult.success("成功！");
    }
}
